//
//  XXPageViewController.m
//  XXPageViewController
//
//  Created by yxlong on 15/5/19.
//  Copyright (c) 2015年 yixin. All rights reserved.
//

#import "XXPageViewController.h"
#import "JTCSM.h"
#import "LCChartView.h"
#import "MyDoubleLabelView.h"
// Tabbar macro
#define _tab_bar_height 45
#define _tab_bar_left_margin 0
// Tabbar item macro
#define _bar_item_width 60
#define _bar_item_tag_base 1000

@interface XXPageViewController ()<UIScrollViewDelegate>
{
    XXPageSelectorView *_tabBarView;
    UIScrollView *_contentContainer;
    UIView *headerView;
    NSUInteger _numberOfPages;
    //When select the page by tap bar item, we disable the method '-scrollViewDidScroll'.
    BOOL scrollByDragging;
}
@property (strong, nonatomic) LCChartView *chartViewLine;
@property (nonatomic,strong) MyDoubleLabelView *leftDataDoubleView;
@property (nonatomic,strong) MyDoubleLabelView *bottomleftView;
@property (nonatomic,strong) MyDoubleLabelView *bottomrightView;
@property (nonatomic,strong) UILabel *headerDateLabel;
- (void)_initializeSubviews;
- (void)cleanupSubviewControllers;
- (void)transitionToIndex:(NSUInteger)index;
- (void)loadViewControllerAtIndex:(NSUInteger)index;
- (UIViewController *)viewControllerAtIndex:(NSUInteger)index;
@end

@implementation XXPageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self _initializeSubviews];
    self.view.backgroundColor = [UIColor whiteColor];
    [JTCSMSingle shareSingle].thevc = self;

    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)_initializeSubviews
{
    if (headerView == nil) {
        [self.view addSubview:[self layoutTableViewHeaderView]];
    }
    
    if(_tabBarView==nil){
        _tabBarView = [[XXPageSelectorView alloc] initWithFrame:CGRectMake(_tab_bar_left_margin, _tab_bar_top_margin, self.view.frame.size.width-_tab_bar_left_margin, _tab_bar_height)];
        _tabBarView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        [self.view addSubview:_tabBarView];
        _tabBarView.backgroundColor = [UIColor whiteColor];
      
        __weak XXPageViewController *weakSelf = self;
        [_tabBarView setBlock_didSelectedAtIndex:^(NSUInteger index){
            [weakSelf transitionToIndex:index];
        }];
        [df lineViewWithHeightofTop:_tab_bar_height superView:_tabBarView spacing:0 color:RGBACOLOR(241, 241, 241, 1) lineHeight:1];
    }
    
    if(_contentContainer==nil){
        float originY = _tab_bar_top_margin+_tab_bar_height;
        _contentContainer = [[UIScrollView alloc] initWithFrame:CGRectMake(0, originY, self.view.frame.size.width, self.view.frame.size.height-originY)];
        _contentContainer.delegate = self;
        _contentContainer.pagingEnabled = YES;
        
        _contentContainer.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
        _contentContainer.bounces  = NO;
        [self.view addSubview:_contentContainer];
        _contentContainer.backgroundColor = RGBACOLOR(241, 241, 241, 1);
        _contentContainer.showsHorizontalScrollIndicator = NO;
//        // 1.集成刷新控件
//        [self setupRefresh];
    }
}
#pragma mark  *  集成刷新控件

- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [_contentContainer addHeaderWithTarget:self action:@selector(headerRereshing)];
    
}
- (void)headerRereshing{
    // 2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(KRefreshTime * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        //getMarriageSeeking(网络请求)
        [[NSNotificationCenter defaultCenter] postNotificationName:@"xxpageChildVCreloadMessage" object:self];
        [_contentContainer headerEndRefreshing];

    });
    
    
}


- (void)cleanupSubviewControllers
{
    for(id elem in self.childViewControllers){
        if([elem isEqual:[NSNull null]]==NO){
            if([elem isKindOfClass:[UIViewController class]]){
                UIViewController *vc = (UIViewController *)elem;
                [vc willMoveToParentViewController:nil];
                [vc.view removeFromSuperview];
                [vc removeFromParentViewController];
            }
        }
    }
}

- (void)reloadData
{
    if(_block_numberOfPages){
        _numberOfPages = _block_numberOfPages();
    }
    else{
        _numberOfPages = 0;
    }
    
    // Clean up all child view controllers
    [self cleanupSubviewControllers];
    if(_subviewControllers==nil){
        _subviewControllers = [NSMutableArray array];
    }
    [_subviewControllers removeAllObjects];
    
    // Reload bar items title
    NSMutableArray *_barItemTitles = [NSMutableArray array];
    if(_numberOfPages>0){
        

        if(_block_titleForPageAtIndex){
            for(int i=0; i< _numberOfPages; i++){
                [_barItemTitles addObject:_block_titleForPageAtIndex(i)];
            }
        }
        else{
            for(int i=0; i< _numberOfPages; i++){
                [_barItemTitles addObject:[NSString stringWithFormat:@"Page %d", i]];
            }
        }
        
        if(_block_viewControllerAtIndex){
            for(int i=0; i< _numberOfPages; i++){
                [_subviewControllers addObject:[NSNull null]];
            }
        }
    }
    _tabBarView.sourceItems = _barItemTitles;
    
#pragma mark  判断光标位置

    if ([self.type isEqualToString:@"qr"] || [self.type isEqualToString:@"mywc"] || [self.type isEqualToString:@"jl"]) {
        [self setSelectedIndex:1];
        [self transitionToIndex:1];

    }else{
        [self setSelectedIndex:0];

    }
    
    [_contentContainer setContentSize:CGSizeMake(_contentContainer.frame.size.width*_numberOfPages, _contentContainer.frame.size.height-KagainChangeHeight)];
}

- (void)transitionToIndex:(NSUInteger)index
{
    NSLog(@"%ld-------%ld",(long)index,(long)_numberOfPages);
    [self setSelectedIndex:index];
    
    [_contentContainer setContentOffset:CGPointMake(index*_contentContainer.frame.size.width, 0) animated:YES];

}

- (void)setSelectedIndex:(NSInteger)index
{
    _selectedIndex = index;
    _tabBarView.selectedIndex = index;
    [self loadViewControllerAtIndex:_selectedIndex];
}

- (void)loadViewControllerAtIndex:(NSUInteger)index
{
    UIViewController *viewController = [self viewControllerAtIndex:index];
    NSLog(@"%@",viewController);
    if([self.childViewControllers containsObject:viewController]==NO){
        [self addChildViewController:viewController];
        viewController.view.frame = CGRectMake(index*_contentContainer.frame.size.width, 0, _contentContainer.frame.size.width, _contentContainer.frame.size.height);
        [_contentContainer addSubview:viewController.view];
        [viewController didMoveToParentViewController:self];
    }
}

- (UIViewController *)viewControllerAtIndex:(NSUInteger)index
{
    if(index>=_subviewControllers.count)
        return nil;
    UIViewController *viewController = [_subviewControllers objectAtIndex:index];
    if([viewController isEqual:[NSNull null]]){
        if(_block_viewControllerAtIndex){
            viewController = _block_viewControllerAtIndex(index);
        }
        [_subviewControllers replaceObjectAtIndex:index withObject:viewController];
    }
    return [_subviewControllers objectAtIndex:index];
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    
    _tabBarView.frame = CGRectMake(_tab_bar_left_margin, _tab_bar_top_margin, self.view.frame.size.width-_tab_bar_left_margin, _tab_bar_height);
    
    float originY = _tab_bar_top_margin+_tab_bar_height;
    _contentContainer.frame = CGRectMake(0, originY, self.view.frame.size.width, self.view.frame.size.height-originY);
}

#pragma mark- scroll view delegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if(!scrollByDragging){
        return;
    }
    CGFloat pageWidth = scrollView.frame.size.width;
    int page = floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
    
    [self setSelectedIndex:page];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    scrollByDragging = YES;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    scrollByDragging = NO;
}

- (BOOL)shouldAutorotate
{
    return NO;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskLandscape;
}

#pragma mark 顶部视图
- (UIView *)layoutTableViewHeaderView{
    
    CGFloat headerviewHeight = _tab_bar_top_margin;
    CGFloat space = 20;
    headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KCONTROLLERWith, headerviewHeight)];
    headerView.backgroundColor = RGBACOLOR(241, 241, 241, 1);
    headerView.userInteractionEnabled = YES;
    
    self.headerDateLabel = [UILabel initWithFrame:CGRectMake(space, 0, KCONTROLLERWith/2, 36) text:@"04月11日" font:13 textAlignment:NSTextAlignmentLeft texcolor:RGBACOLOR(51, 51, 51, 1) backgroundColor:nil];
    [headerView addSubview:self.headerDateLabel];
    
    CGFloat dateImageSize = 20;
    UIImageView *dateImageV = [[UIImageView alloc]initWithFrame:CGRectMake(KCONTROLLERWith-space-dateImageSize, 8, dateImageSize, dateImageSize)];
    dateImageV.image = [UIImage imageNamed:@"明细_日历.png"];
    [headerView addSubview:dateImageV];
    dateImageV.userInteractionEnabled = YES;
//    [df addTapGestureRecognizerWithTarget:self action:@selector(gotoDBVC) andaddView:dateImageV];
    
    CGFloat dataViewWidth = KCONTROLLERWith*0.328;
    UIView *leftdataView = [[UIView alloc]initWithFrame:CGRectMake(0, KVIEW_Y(self.headerDateLabel), dataViewWidth, 120)];
    leftdataView.backgroundColor = [UIColor whiteColor];
    [headerView addSubview:leftdataView];
    
    self.leftDataDoubleView = [[MyDoubleLabelView alloc]initWithFrame:CGRectMake(20, 30, leftdataView.LC_width-20, 0) leftTitleFontsize:17 titlecolor:RGBACOLOR(51, 51, 51, 1) contentFontsize:12 contentcolor:[df colorWithHexString:@"666666" alpha:1]];
    [leftdataView addSubview:self.leftDataDoubleView];
    [self.leftDataDoubleView setvalueWithModel:@{KDoubleLabelTitle:@"183450.00",KDoubleLabelContent:@"32884387笔"}];
    NSString *str = @"共计";
    CGFloat font = 9;
    CGRect alertRect = [df labelHeightWithContent:str width:100 font:font];
    UILabel *alertLabel = [UILabel initWithFrame:CGRectMake(20, KVIEW_Y(self.leftDataDoubleView)+5, alertRect.size.width+5, alertRect.size.height+5) text:str font:font textAlignment:NSTextAlignmentCenter texcolor:[UIColor whiteColor] backgroundColor:[df colorWithHexString:@"ffa018" alpha:1]];
    [df layerWithView:alertLabel radius:4 width:0 color:nil];
    [leftdataView addSubview:alertLabel];
    
    UIView *rightdataView = [[UIView alloc]initWithFrame:CGRectMake(KCONTROLLERWith*0.328+1, KVIEW_Y(self.headerDateLabel), KCONTROLLERWith-dataViewWidth-1, 120)];
    rightdataView.backgroundColor = [UIColor whiteColor];
    [headerView addSubview:rightdataView];
    _chartViewLine = [LCChartView chartViewWithType:LCChartViewTypeLine];
    _chartViewLine.frame = CGRectMake(20, 10, rightdataView.LC_width-1, 90);
    [rightdataView addSubview:self.chartViewLine];
    LCChartViewModel *model = [LCChartViewModel modelWithColor:KZhuTiRGB plots:[self randomArrayWithCount:1000] project:@""];
    [self.chartViewLine showChartViewWithYAxisMaxValue:1000 dataSource:@[model]];
    
    
    
    UIView *bottomdataView = [[UIView alloc]initWithFrame:CGRectMake(0, 156, KCONTROLLERWith, 80)];
    bottomdataView.backgroundColor = [UIColor whiteColor];
    [df lineViewWithWidthtofLeft:KCONTROLLERWith/2-0.5 superView:bottomdataView spacing:10 color:RGBACOLOR(241, 241, 241, 1) lineWidth:1];
    [df newlineViewWithHeightofTop:1 superView:bottomdataView spacing:20 color:RGBACOLOR(241, 241, 241, 1) lineHeight:1];
    [headerView addSubview:bottomdataView];
    
    self.bottomleftView = [[MyDoubleLabelView alloc]initWithFrame:CGRectMake(0, 0, KCONTROLLERWith/2, bottomdataView.LC_height) titleFontsize:17 titlecolor:RGBACOLOR(51, 51, 51, 1) contentFontsize:12 contentcolor:[df colorWithHexString:@"666666" alpha:1]];
    [bottomdataView addSubview:self.bottomleftView];
    [self.bottomleftView InsertSpacesetvalueWithModel:@{KDoubleLabelTitle:@"183450.00",KDoubleLabelContent:@"净收益（元）"}changeLabelY:10];
    
    self.bottomrightView = [[MyDoubleLabelView alloc]initWithFrame:CGRectMake(KCONTROLLERWith/2, 0, KCONTROLLERWith/2, bottomdataView.LC_height) titleFontsize:17 titlecolor:RGBACOLOR(51, 51, 51, 1) contentFontsize:12 contentcolor:[df colorWithHexString:@"666666" alpha:1]];
    [bottomdataView addSubview:self.bottomrightView];
    [self.bottomrightView InsertSpacesetvalueWithModel:@{KDoubleLabelTitle:@"183450.00",KDoubleLabelContent:@"手续费（元）"}changeLabelY:10];
    [df newlineViewWithHeightofTop:236 superView:headerView spacing:0 color:RGBACOLOR(241, 241, 241, 1) lineHeight:10];
    return headerView;
    
}
- (NSArray *)randomArrayWithCount:(NSInteger)dataCounts {
    NSMutableArray *array = [[NSMutableArray alloc] init];
    for (int i = 0; i < dataCounts; i++) {
        NSString *number = [NSString stringWithFormat:@"%d.%d%d",arc4random_uniform(1000),arc4random_uniform(9),arc4random_uniform(9)];
        [array addObject:number];
    }
    return array.copy;
}

@end
